// 单例模式
export const loadScript = (function () {
  const caches = [] // 缓存列表

  return (url) => {
    if (caches.includes(url)) return Promise.resolve()

    return new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.type = 'text/javascript'

      if (script.readyState) {
        script.onreadystatechange = function () {
          if (script.readyState == 'loaded' || script.readyState == 'complete') {
            script.onreadystatechange = null
            caches.push(url)
            resolve()
          }
        }
      } else {
        script.onload = function () {
          caches.push(url)
          resolve()
        }
        script.onerror = function () {
          console.log(`load js fail:${url}`)
          reject()
        }
      }

      script.src = url
      document.body.appendChild(script)
    })
  }
})()
